import axios from 'axios'
import Vue from 'vue'
import router from './router'

const http = axios.create({
    // baseURL: 'http://localhost:3000/admin/api'
    baseURL: process.env.VUE_APP_API_URL || '/admin/api'
})

// 请求拦截器 将token传入请求头Request Header
http.interceptors.request.use(config => {
    // 将token值传入请求头,"Bearer+空格"是行业规范,一看见Bearer(持票人,也就是被校验者)就知道是token验证
    if (localStorage.token) {
        config.headers.Authorization = 'Bearer ' + localStorage.token
    }
    return config
}, err => {
    return Promise.reject(err)
})  

// 响应拦截器
http.interceptors.response.use(res => {
    return res
  }, err => {
    // console.log(err.response.data.message);
    if (err.response.data.message) {
        Vue.prototype.$message({
            type: 'error',
            message: err.response.data.message
        })
        if (err.response.status === 401) {
            router.push('/login')
        }
    }
    return Promise.reject(err)
})

export default http